// 拓扑图预览
angular.module('HTRD_AutoConsole.A').directive('quneeEditer',['$window', '$timeout', '$interval', '$stateParams', '$rootScope', 'ManagerProcessQuneeServ', 'DialogServ', 'SocketServ', 'AlertServ', 'ParseMapServ', 'DateParseServ',
function($window, $timeout, $interval, $stateParams, $rootScope, ManagerProcessQuneeServ, DialogServ, SocketServ, AlertServ, ParseMapServ, DateParseServ) {
  var link = function(s, e) {
      var $scope, $node, testCount = 0;
      var quneeStart, strapModal;

      // 流程id
      var processId = 0;

      // 执行id
      var execId;

      var nodeStatusMap = {
        // -1: 'st_unknow',  未知状态

        // 流程初始化
        0: 'init'
        ,
        // # 正在检测
        1: 'check',

        // # 流程检测错误
        2: 'checkError',

        // # 节点检测－脚本错误
        3: 'checkScriptError',

        // # 节点检测－主机错误
        4: 'checkError',

        // # 检测成功
        5: 'checkSuccess',

        // # 正在执行
        6: 'running',

        // # 执行错误
        7: 'runError',

        // # 执行超时
        8: 'runTimeout',

        // # 执行成功
        9: 'runSuccess',

        // # 等待用户确认
        10: 'waitUserConfirm',

        // # 停止执行
        11: 'quit',

        // # 正在停止
        12: 'st_stopping',

        // # 暂停执行
        13: 'pause',

        // # 正在暂停
        14: 'st_pausing',

        // # 等待用户输入
        15: 'st_waiting_for_input',

        // # 执行单个节点/重做
        16: 'st_running_one',

        // # 执行单个节点/重做 成功
        17: 'st_run_one_ok',

        // # 执行单个节点/重做 失败
        18: 'st_run_one_err',

        // # 用户拒绝
        19: 'st_confirm_refused',

        // 执行完成但有错误
        20: 'runSuccessAndNodeError',

        // 手工接管后的执行结果：成功
        21: 'takeOverSucc',

        // 手工接管后的执行结果：失败
        22: 'takeOverError'
      };

      // 如果状态为数字 则转换
      var quneeStateMap = {
        0: 'init', // 默认(1级分类)
        1: 'check', // 检测中(1级分类)
        2: 'exec', // 执行中(1级分类)
        3: 'checkError', // 检测异常(2级分类)
        4: 'checkSuccess', // 检测成功(2级分类)
        5: 'execSuccess' // 执行成功
      };

      // 执行中状态
      var runningMap = {
        0: 'pause',
        1: 'running'
      };

      // 执行中节点状态
      var runningNodeMap = {
        0: 'error',
        1: 'overtime',
        2: 'runningSuccess'
      };

      // var quneeRefTypeMap = {
      //   0: 'basicNode',
      //   1: 'logicNode',
      //   2: 'userConfirmNode',
      //   3: 'userInputNode',
      //   4: 'groupNode',
      //   5: 'startNode',
      //   6: 'endNode',
      //   7: 'closeNode',
      //   8: 'restartNode'
      // };

      var quneeRefTypeMap = {
        1: 'basicNode',
        2: 'userConfirmNode',
        3: 'groupNode',
        4: 'startNode',
        5: 'endNode',
        6: 'closeNode',
        7: 'restartNode'
      };

      // 流程执行结果字典
      var quneeExecStatus = {
        6: '执行中',
        7: '执行错误',
        8: '执行超时',
        9: '执行成功',
        10: '等待确认',
        11: '手工终止',
        12: '正在停止',
        13: '已暂停',
        14: '正在暂停',
        19: '用户不认可终止',
        20: '执行完成但有错误',
        21: '手工接管后的执行结果：成功',
        22: '手工接管后的执行结果：失败'
      };

      var resetNodes = function() {
        var refId;
        $scope.nodeList = quneeParseNodeJSON($scope.pipeline);

        // 先获取全部node
        selfJson = JSON.parse($scope.getChartJSON());
        selfJson.datas.map(function(selfItem, index) {

          // 更新普通节点
          if (selfItem._className === 'Q.Node') {

            if (!!!selfItem.json.properties.data.id) {
              refId = selfItem.json.properties.data.$ref;
              selfItem.json.properties.data = selfJson.refs[refId];
            };

            selfItem.json.properties.data.infoData.status = 'init';
            getNodeData(selfItem.json.properties.data, selfItem.json);
          };
        });

        updateJSON(selfJson);
      };

      var dupRemove = function(arr, isNotReverse) {
        var result = [];
        var ids = [];

        if (!!!isNotReverse) {
          // 相同id的节点最终显示后面的状态
          arr.reverse();
        };

        arr.map(function(item) {

          // 不存在才加入结果集
          if (ids.indexOf(item.id) === -1) {
            result.push(item);
            ids.push(item.id);
          };
        });

        return result;
      };

      // 转换json字符串 , 组装完整的json数据
      var quneeParseNodeJSON = function(nodeList, nodeStatusList) {
        var nodeJSON;

        if (typeof nodeList === 'string') {
          nodeJSON = JSON.parse(nodeList);
        } else {
          nodeJSON = nodeList;
        };

        // 判断节点状态列表内是否有数据 没有则代表初始化状态
        if (!!nodeStatusList) {

          for (var key in nodeJSON) {

            if (key === 'groups') {
              nodeStatusList.map(function(item) {
                nodeJSON[key].map(function(group) {

                  // 循环组内的节点状态
                  group.nodes.map(function(node) {

                    if (node.id === (item.node_id || item.id)) {
                      node.infoData.status = nodeStatusMap[item.status] || 'init';
                    };

                    node.infoData.type = quneeRefTypeMap[node.infoData.ref_type];
                  });
                });
              });
            } else {
              nodeStatusList.map(function(item) {
                nodeJSON[key].map(function(node) {

                  if (node.id === (item.node_id || item.id)) {
                    node.infoData.status = nodeStatusMap[item.status] || 'init';
                  };

                  node.infoData.type = quneeRefTypeMap[node.infoData.ref_type];
                });
              });
            }
          };
        } else {

          for (var key in nodeJSON) {
            nodeJSON[key].map(function(node) {
              node.infoData.status = 'init';
              node.infoData.type = quneeRefTypeMap[node.infoData.ref_type];
            });
          };
        };
        return nodeJSON;
      };

      var updateQuneeStateBtn = function() {
        switch ($scope.quneeState) {

          // 初始化
          case 'init':
          console.log('init');
            // $node.find('.htrd-l-bg-black i').removeClass().addClass('htrd-icon-check');
            // $node.find('.htrd-l-bg-black i').removeClass().addClass('htrd-icon-random');
            // $node.find('.htrd-l-bg-black i').removeClass().addClass('htrd-icon-pause');
            $node.find('.qunee-quit').addClass('default btn-outline').attr("disabled", true);
            $node.find('.qunee-quit i').removeClass().addClass('htrd-icon-stop-click')
            $node.find('.qunee-pause').hide();
            $node.find('.qunee-continue').hide();
            $node.find('.qunee-check').show();
            $node.find('.htrd-c-button-group').show();
            $scope.stateConfig = {
              check: true,
              start: true,
              continue: false,
              pause: true,
              quit: false,
            };
            break;

          // 检测中
          case 'check':
          console.log('check');
            $node.find('.qunee-check').addClass('default btn-outline').attr("disabled", true);
            $node.find('.qunee-check i').removeClass().addClass('htrd-icon-check-click');

            $node.find('.qunee-quit').addClass('default btn-outline').attr("disabled", true);
            $node.find('.qunee-quit i').removeClass().addClass('htrd-icon-stop-click');

            $node.find('.qunee-start').addClass('default btn-outline').attr("disabled", true);
            $node.find('.qunee-start i').removeClass().addClass('htrd-icon-random-click');

            $node.find('.qunee-pause').hide();
            $node.find('.qunee-continue').hide();
            $node.find('.htrd-c-button-group').show();

            ParseMapServ.setItem(processId, 'check','lastState');

            $scope.stateConfig = {
              check: false,
              start: false,
              pause: false,
              continue: false,
              quit: false,
            };
            break;

          // 检测异常
          case 'checkError':
          console.log('checkError');
            $node.find('.qunee-check').removeClass('default btn-outline').attr("disabled", false);
            $node.find('.qunee-check i').removeClass().addClass('htrd-icon-check');
            // $node.find('.qunee-start').addClass('default btn-outline');
            $node.find('.qunee-quit').addClass('default btn-outline').attr("disabled", true);
            $node.find('.qunee-check i').removeClass().addClass('htrd-icon-stop-click')
            $node.find('.qunee-pause').hide();
            // $node.find('.qunee-continue').hide();
            $node.find('.htrd-c-button-group').show();
            // $node.find('.qunee-start').show();

            $scope.stateConfig = {
              check: true,
              start: false,
              continue: false,
              pause: false,
              quit: false
            };

            if (!$node.find('.qunee-start').is(":hidden")) {
              $node.find('.qunee-start').addClass('default btn-outline').attr("disabled", true);
              $node.find('.qunee-start i').removeClass().addClass('htrd-icon-random-click');
            };

            if (!$node.find('.qunee-continue').is(":hidden")) {
              $node.find('.qunee-continue').addClass('default btn-outline').attr("disabled", true);
              $node.find('.qunee-continue i').removeClass().addClass('htrd-icon-random-click');
            };

            if (!$scope.init) {
              // AlertServ.showError('检测异常');
            } else {
              $scope.init = false;
            };
            break;

          // 检测完成
          case 'checkSuccess':
          console.log('checkSuccess');
            $node.find('.htrd-c-button-group').show()
            $scope.stateConfig = {
              check: true,
              start: true,
              continue: true,
              pause: false,
              quit: false
            };

            if ($scope.isCheck) {
              $node.find('.qunee-pause').hide();

              if (!$node.find('.qunee-start').is(":hidden")) {
                $node.find('.qunee-start').removeClass('default btn-outline').attr("disabled", false);
                $node.find('.qunee-start i').removeClass().addClass('htrd-icon-random');
              };

              if (!$node.find('.qunee-continue').is(":hidden")) {
                $node.find('.qunee-continue').removeClass('default btn-outline').attr("disabled", false);
                $node.find('.qunee-continue i').removeClass().addClass('htrd-icon-random-click');
              };

              if (!$scope.init) {
                $node.find('.qunee-continue').hide();
                $node.find('.qunee-start').show();
              } else {
                $node.find('.qunee-continue').hide();
                $node.find('.qunee-start').show();
                $scope.init = false;
              };
              $node.find('.qunee-check').removeClass('default btn-outline').attr("disabled", false);
              $node.find('.qunee-check i').removeClass().addClass('htrd-icon-check');

              $node.find('.qunee-quit').addClass('default btn-outline').attr("disabled", true);
              $node.find('.qunee-quit i').removeClass().addClass('htrd-icon-stop-click');
            } else {
              $scope.stateConfig = {
                check: false,
                start: true,
                pause: true,
                continue: true,
                quit: true
              };

              $node.find('.qunee-start').hide();
              $node.find('.qunee-continue').hide();
              $node.find('.qunee-check').addClass('default btn-outline').attr("disabled", true);
              $node.find('.qunee-check i').removeClass().addClass('htrd-icon-check-click');
              $node.find('.qunee-quit').show().removeClass('default btn-outline').attr("disabled", false);
              $node.find('.qunee-quit i').removeClass().addClass('htrd-icon-stop');
              $node.find('.qunee-pause').show().removeClass('default btn-outline').attr("disabled", false);
              $node.find('.qunee-pause i').removeClass().addClass('htrd-icon-pause');
            };
            break;

          // 等待执行 / 执行中 / 继续执行
          case 'running':
            $node.find('.qunee-check').addClass('default btn-outline').attr("disabled", true);
            $node.find('.qunee-check i').removeClass().addClass('htrd-icon-check-click');
            $node.find('.qunee-pause').removeClass('default btn-outline').attr("disabled", false);
            $node.find('.qunee-pause i').removeClass().addClass('htrd-icon-pause');
            $node.find('.qunee-quit').removeClass('default btn-outline').attr("disabled", false);
            $node.find('.qunee-quit i').removeClass().addClass('htrd-icon-stop');
            $node.find('.qunee-pause').show();
            $node.find('.qunee-continue').hide();
            $node.find('.qunee-start').hide();
            $scope.stateConfig = {
              check: false,
              start: false,
              continue: false,
              pause: true,
              quit: true
            };
            ParseMapServ.setItem(processId, 'running', 'lastState');
            break;

          // 暂停
          case 'pause':
            $node.find('.qunee-check').addClass('default btn-outline').attr("disabled", true);
            $node.find('.qunee-check i').removeClass().addClass('htrd-icon-check-click');
            $node.find('.qunee-pause').removeClass('default btn-outline').attr("disabled", false);
            $node.find('.qunee-pause i').removeClass().addClass('htrd-icon-pause');
            $node.find('.qunee-continue').removeClass('default btn-outline').attr("disabled", false);
            $node.find('.qunee-continue i').removeClass().addClass('htrd-icon-random');
            $node.find('.qunee-quit').removeClass('default btn-outline').attr("disabled", false);
            $node.find('.qunee-quit i').removeClass().addClass('htrd-icon-stop');
            $node.find('.qunee-continue').show();
            $node.find('.qunee-pause').hide();
            $node.find('.qunee-start').hide();
            $scope.stateConfig = {
              check: true,
              start: false,
              continue: true,
              pause: true,
              quit: true
            };
            $timeout.cancel(quneeStart);
            ParseMapServ.setItem(processId, 'pause', 'lastState');
            break;

          case 'waitUserConfirm':

            $node.find('.qunee-check').addClass('default btn-outline');
            $node.find('.qunee-pause').removeClass('default btn-outline');
            $node.find('.qunee-continue').removeClass('default btn-outline');
            $node.find('.qunee-quit').removeClass('default btn-outline');
            $node.find('.qunee-continue').show();
            $node.find('.qunee-pause').hide();
            $node.find('.qunee-start').hide();
            $scope.stateConfig = {
              check: true,
              start: false,
              continue: true,
              pause: true,
              quit: true
            };
            $timeout.cancel(quneeStart);
            ParseMapServ.setItem(processId, 'pause', 'lastState');
            break;

          case 'parseError':
            $node.find('.qunee-check').addClass('default btn-outline').attr("disabled", true);
            $node.find('.qunee-check i').removeClass().addClass('htrd-icon-check-click');
            $node.find('.qunee-pause').removeClass('default btn-outline').attr("disabled", false);
            $node.find('.qunee-pause i').removeClass().addClass('htrd-icon-pause');
            $node.find('.qunee-continue').removeClass('default btn-outline').attr("disabled", false);
            $node.find('.qunee-continue i').removeClass().addClass('htrd-icon-random');
            $node.find('.qunee-quit').removeClass('default btn-outline').attr("disabled", false);
            $node.find('.qunee-quit i').removeClass().addClass('htrd-icon-stop');
            $node.find('.qunee-continue').show();
            $node.find('.qunee-pause').hide();
            $node.find('.qunee-start').hide();
            $scope.stateConfig = {
              check: true,
              start: false,
              continue: true,
              pause: true,
              quit: true
            };
            $timeout.cancel(quneeStart);
            ParseMapServ.setItem(processId, 'pause', 'lastState');
            break;

          case 'runError':
            $node.find('.qunee-check').addClass('default btn-outline').attr("disabled", true);
            $node.find('.qunee-check i').removeClass().addClass('htrd-icon-check-click');
            $node.find('.qunee-pause').addClass('default btn-outline').attr("disabled", true);
            $node.find('.qunee-pause i').removeClass().addClass('htrd-icon-pause-click');
            $node.find('.qunee-continue').addClass('default btn-outline').attr("disabled", true);
            $node.find('.qunee-continue i').removeClass().addClass('htrd-icon-random-click');
            $node.find('.qunee-quit').addClass('default btn-outline').attr("disabled", true);
            $node.find('.qunee-quit i').removeClass().addClass('htrd-icon-stop-click');
            $node.find('.qunee-continue').show();
            $node.find('.qunee-pause').hide();
            $node.find('.qunee-start').hide();
            $scope.stateConfig = {
              check: false,
              start: false,
              continue: false,
              pause: false,
              quit: false
            };
            $timeout.cancel(quneeStart);
            ParseMapServ.setItem(processId, 'pause', 'lastState');
            break;

          // 手工终止
          case 'manualQuit':
            $node.find('.qunee-check').addClass('default btn-outline').attr("disabled", true);
            $node.find('.qunee-check i').removeClass().addClass('htrd-icon-check-click');
            $node.find('.qunee-continue').hide();
            $node.find('.qunee-pause').show();
            $node.find('.qunee-pause').addClass('default btn-outline').attr("disabled", true);
            $node.find('.qunee-pause i').removeClass().addClass('htrd-icon-pause-click');
            $node.find('.qunee-quit').addClass('default btn-outline').attr("disabled", true);
            $node.find('.qunee-quit i').removeClass().addClass('htrd-icon-stop-click');
            $scope.stateConfig = {
              check: false,
              start: false,
              continue: false,
              pause: false,
              quit: false
            };

            if ($scope.quitState) {
              $node.find('.qunee-start').hide();
              // $node.find('.qunee-pause').hide();
              $node.find('.qunee-continue').hide();

              if ($scope.quitState === 'start') {
                $node.find('.qunee-start').show().addClass('default btn-outline').attr("disabled", true);
                $node.find('.qunee-start i').removeClass().addClass('htrd-icon-random-click')
              }
              else if ($scope.quitState === 'continue') {
                $node.find('.qunee-continue').show().addClass('default btn-outline').attr("disabled", true);
                $node.find('.qunee-continue i').removeClass().addClass('htrd-icon-random-click');
              }
              else if ($scope.quitState === 'pause'){
                $node.find('.qunee-pause').show().addClass('default btn-outline').attr("disabled", true);
                $node.find('.qunee-pause i').removeClass().addClass('htrd-icon-pause-click');
              };
            } else {

              if (!$node.find('.qunee-start').is(":hidden")) {
                $node.find('.qunee-start').addClass('default btn-outline').attr("disabled", true);
                $node.find('.qunee-start i').removeClass().addClass('htrd-icon-random-click');
              };

              if (!$node.find('.qunee-continue').is(":hidden")) {
                $node.find('.qunee-continue').addClass('default btn-outline').attr("disabled", true);
                $node.find('.qunee-continue i').removeClass().addClass('htrd-icon-random-click');
              };

              if (!$node.find('.qunee-pause').is(":hidden")) {
                $node.find('.qunee-pause').addClass('default btn-outline').attr("disabled", true);
                $node.find('.qunee-pause i').removeClass().addClass('htrd-icon-pause-click');
              };
            };
            ParseMapServ.setItem(processId, 'manualQuit','lastState');
            break;


          // 全部执行成功
          case 'runSuccess':
            $node.find('.qunee-start').hide();
            $node.find('.qunee-quit').addClass('default btn-outline').attr("disabled", true);
            $node.find('.qunee-quit i').removeClass().addClass('htrd-icon-stop-click');

            if (!$node.find('.qunee-continue').is(":hidden")) {
              $node.find('.qunee-continue').addClass('default btn-outline').attr("disabled", true);
              $node.find('.qunee-continue i').removeClass().addClass('htrd-icon-random-click');
            };

            if (!$node.find('.qunee-pause').is(":hidden")) {
              $node.find('.qunee-pause').addClass('default btn-outline').attr("disabled", true);
              $node.find('.qunee-pause i').removeClass().addClass('htrd-icon-pause-click');
            };
            $scope.stateConfig = {
              check: false,
              start: false,
              continue: false,
              pause: false,
              quit: false
            };

            strapModal = DialogServ.modal({
              'scope': $scope,
              'templateUrl': 'view/console/modal/quneeEditorExecResult.html'
            });
            strapModal.$promise.then(strapModal.show);
            break;

          case 'runSuccessAndNodeError':

            // AlertServ.showSuccess('流程执行成功了');
            $node.find('.qunee-start').hide();
            $node.find('.qunee-quit').addClass('default btn-outline').attr("disabled", true);
            $node.find('.qunee-quit i').removeClass().addClass('htrd-icon-stop-click');

            if (!$node.find('.qunee-continue').is(":hidden")) {
              $node.find('.qunee-continue').addClass('default btn-outline').attr("disabled", true);
              $node.find('.qunee-continue i').removeClass().addClass('htrd-icon-random-click');
            };

            if (!$node.find('.qunee-pause').is(":hidden")) {
              $node.find('.qunee-pause').addClass('default btn-outline').attr("disabled", true);
              $node.find('.qunee-pause i').removeClass().addClass('htrd-icon-pause-click');
            };
            $scope.stateConfig = {
              check: false,
              start: false,
              continue: false,
              pause: false,
              quit: false
            };

            strapModal = DialogServ.modal({
              'scope': $scope,
              'templateUrl': 'view/console/modal/quneeEditorExecResult.html'
            });
            strapModal.$promise.then(strapModal.show);
            break;

          // 执行错误
          case 'error':
            $node.find('.qunee-check').removeClass('default btn-outline').attr("disabled", false);
            $node.find('.qunee-check i').removeClass().addClass('htrd-icon-check');
            $node.find('.qunee-continue').removeClass('default btn-outline').attr("disabled", false);
            $node.find('.qunee-continue i').removeClass().addClass('htrd-icon-random');
            $node.find('.qunee-quit').removeClass('default btn-outline').attr("disabled", false);
            $node.find('.qunee-quit i').removeClass().addClass('htrd-icon-stop');
            $node.find('.qunee-continue').show();
            $node.find('.qunee-pause').hide();
            $node.find('.qunee-start').hide();
            $scope.stateConfig = {
              check: true,
              start: false,
              continue: true,
              pause: false,
              quit: true
            };
            break;

          case 'runTimeout':
            $node.find('.qunee-check').addClass('default btn-outline').attr("disabled", true);
            $node.find('.qunee-check i').removeClass().addClass('htrd-icon-check');
            $node.find('.qunee-pause').addClass('default btn-outline').attr("disabled", true);
            $node.find('.qunee-pause i').removeClass().addClass('htrd-icon-pause');
            $node.find('.qunee-continue').addClass('default btn-outline').attr("disabled", true);
            $node.find('.qunee-continue i').removeClass().addClass('htrd-icon-random');
            $node.find('.qunee-quit').addClass('default btn-outline').attr("disabled", true);
            $node.find('.qunee-quit i').removeClass().addClass('htrd-icon-stop');
            $node.find('.qunee-continue').show();
            $node.find('.qunee-pause').hide();
            $node.find('.qunee-start').hide();
            $scope.stateConfig = {
              check: false,
              start: false,
              continue: false,
              pause: false,
              quit: false
            };
            $timeout.cancel(quneeStart);
            ParseMapServ.setItem(processId, 'pause', 'lastState');
            break;

          // 执行超时
          case 'overtime':
            $node.find('.qunee-check').removeClass('default btn-outline').attr("disabled", false);
            $node.find('.qunee-check i').removeClass().addClass('htrd-icon-check');
            $node.find('.qunee-continue').removeClass('default btn-outline').attr("disabled", false);
            $node.find('.qunee-continue i').removeClass().addClass('htrd-icon-random');
            $node.find('.qunee-quit').removeClass('default btn-outline').attr("disabled", false);
            $node.find('.qunee-quit i').removeClass().addClass('htrd-icon-stop');
            $node.find('.qunee-continue').show();
            $node.find('.qunee-pause').hide();
            $node.find('.qunee-start').hide();
            $scope.stateConfig = {
              check: true,
              start: false,
              continue: true,
              pause: false,
              quit: true
            };
            break;

          case 'waitConfirmOrSubmit':
            $node.find('.qunee-check').addClass('default btn-outline').attr("disabled", true);
            $node.find('.qunee-check i').removeClass().addClass('htrd-icon-check');
            $node.find('.qunee-pause').removeClass('default btn-outline').attr("disabled", false);
            $node.find('.qunee-pause i').removeClass().addClass('htrd-icon-pause');
            $node.find('.qunee-quit').removeClass('default btn-outline').attr("disabled", false);
            $node.find('.qunee-quit i').removeClass().addClass('htrd-icon-start');
            $node.find('.qunee-continue').hide();
            $node.find('.qunee-pause').show();
            $node.find('.qunee-start').hide();
            $scope.stateConfig = {
              check: true,
              start: false,
              continue: false,
              pause: false,
              quit: true
            };

            ParseMapServ.setItem(processId, 'waitConfirmOrSubmit', 'lastState');
            break;
          default:
        }
      };

      var toggleRadio = function(isActive) {
        $scope.userConfirmModel = $scope.userConfirmModel || {};
        $scope.userConfirmModel.is_exec = isActive;
      };

      var toggleTakeRadio = function(isActive) {
        $scope.userEditorTakeOverModel = $scope.userEditorTakeOverModel || {};
        $scope.userEditorTakeOverModel.check = isActive;
      };

      var socketPullData = function(data) {
        $node.trigger('qunee.stateChange', data);
      };

      var getQuneeNodeInfo = function(data) {
        $scope.$apply(function () {
          $scope.historyListState = false;
          $scope.processInfoState = false;
          $scope.nodeInfoState = true;
        });
      };

      var getQuneeProcessInfo = function() {
        ManagerProcessQuneeServ.getManagerProcessQuneeInfo({
          id: processId
        })
        .then(function(ret) {

          if (ret.status === 200) {
            $scope.processInfo = ret.results;
          } else {

          };
        });
      };

      var getQuneeHistoryList = function() {
        ManagerProcessQuneeServ.getManagerProcessQuneeHistoryList({
          id: processId
        })
        .then(function(ret) {

          if (ret.status === 200) {

            // 格式化时间
            ret.results.map(function(item, index) {
              item.started_at = DateParseServ.dateParse(item.started_at);
              item.resultStatusStr = quneeExecStatus[item.result_status];
            });

            $scope.historyList = ret.results;
          } else {
            $scope.historyList = [];
            AlertServ.showError(ret.msg);
          };
        });
      };

      var getUserList = function() {
        $scope.userList = [
          {
            id: 1,
            title: '张健'
          }
        ];

        // ManagerProcessQuneeServ.getUserList()
        // .then(function(ret) {
        //
        //   if (ret.status === 200) {
        //     $scope.userList = [];
        //     ret.results.data.map(function(item, index) {
        //       $scope.userList.push({
        //         id: item.id,
        //         title: item.username
        //       });
        //     });
        //   }
        // });
      };

      var activeUser = function(item) {
        $scope.userConfirmModel.user_id = item.id;
      };

      // 用户用户确认/重做弹框
      var submitUserConfirm = function() {
        delete $scope.userConfirmModel.errerMsg;
        $scope.userConfirmModel.id = execId;
        // $scope.userConfirmModel.node_id =
        $scope.userConfirmModel.is_exec = $scope.userConfirmModel.is_exec;

        if (!!!$scope.userConfirmModel.user_id) {
          $scope.userConfirmModel.errerMsg = '请选择用户';
          return false;
        };

        if (!!!$scope.userConfirmModel.password) {
          $scope.userConfirmModel.errerMsg = '请输入密码';
          return false;
        };

        // 选中不认可 同时 未填写不认可理由
        if (!!!$scope.userConfirmModel.is_exec && !!!$scope.userConfirmModel.result_info) {
          $scope.userConfirmModel.errerMsg = '请输入不认可理由';
          return false;
        };

        $scope.socketPullData('requesting');
        ManagerProcessQuneeServ.submitManagerProcessQuneeUserConfirm($scope.userConfirmModel)
        .then(function(ret) {

          if (ret.status === 200) {
            // AlertServ.showSuccess(ret.msg);
            strapModal.hide();
            $scope.selectDefaultText = '请选择用户';


            if (!!$scope.userConfirmModel.is_exec) {
              $scope.quitState = 'running';
              $scope.quneeState = 'running';
              $scope.socketPullData($scope.quneeState);

              // 清空dialog 下次用户确认继续可以显示
              strapModal = null;
              $scope.userConfirmModel = {};
            } else {
              $scope.quneeState = 'manualQuit';
              $scope.socketPullData('noApproval');
            };
            updateQuneeStateBtn();
          } else {
            $scope.userConfirmModel.errerMsg = ret.msg || '密码错误, 请重试';
            // AlertServ.showError();
          };
        });
      };

      // 用户接管
      var submitEditorTakeOver = function() {
        var data = {
          id: execId,
          status: $scope.userEditorTakeOverModel.check,
          result_info: $scope.userEditorTakeOverModel.remark.trim()
        };
        $scope.socketPullData('requesting');
        ManagerProcessQuneeServ.ManagerProcessQuneeManualNozzleNode(data)
        .then(function(ret) {

          if (ret.status === 200) {
            AlertServ.showSuccess(ret.msg);
            strapModal.hide();
            $scope.userEditorTakeOverModel = {
              check: 1
            };
            $scope.quneeState = 'manualQuit';
            updateQuneeStateBtn();

            if (!$node.find('.qunee-start').is(":hidden")) {
              ParseMapServ.setItem(processId, 'start', 'quitState');
            };

            if (!$node.find('.qunee-continue').is(":hidden")) {
              ParseMapServ.setItem(processId, 'continue', 'quitState');
            };

            if (!$node.find('.qunee-pause').is(":hidden")) {
              ParseMapServ.setItem(processId, 'pause', 'quitState');
            };

            // if (!!$scope.userEditorTakeOverModel.check) {
            //   $scope.socketPullData('takeOverSucc');
            // } else {
            //   $scope.socketPullData('takeOverError');
            // };
          } else {
            AlertServ.showError(ret.msg);
          }
        });
      };



      // 手动终止确认
      var submitProcessQuit = function() {
        $scope.socketPullData('requesting');
        ManagerProcessQuneeServ.ManagerProcessQuneeQuit({
          id: execId,
          result_info: $scope.userEditorQuitModel.remark
        })
        .then(function(ret) {

          if (ret.status === 200) {
            $scope.userEditorQuitModel = {};
            strapModal.hide();
            $timeout.cancel(quneeStart);
            $scope.quneeState = 'manualQuit';

            if (!$node.find('.qunee-start').is(":hidden")) {
              ParseMapServ.setItem(processId, 'start', 'quitState');
            };

            if (!$node.find('.qunee-continue').is(":hidden")) {
              ParseMapServ.setItem(processId, 'continue', 'quitState');
            };

            if (!$node.find('.qunee-pause').is(":hidden")) {
              ParseMapServ.setItem(processId, 'pause', 'quitState');
            };

            AlertServ.showSuccess(ret.msg || '终止成功');
            updateQuneeStateBtn();
            $scope.socketPullData('quit');
          } else {
            AlertServ.showError(ret.msg);
          };
        });
      };


      // 初始化页面log
      var getManagerProcessQuneeLogList = function(execId) {
        ManagerProcessQuneeServ.getManagerProcessQuneeLogList({
          id: execId
        })
        .then(function(ret) {

          if (ret.status === 200) {

            if ($scope.logList.length > 0) {
              var logList = $scope.logList.concat(ret.results);
              $scope.logList = dupRemove(logList, true);
            } else {
              $scope.logList = ret.results;
            };

            $scope.logList.map(function(item) {
              item.created_at = DateParseServ.dateParse(item.created_at);
            });
          } else {
            AlertServ.showError(ret.msg);
          };
        });
      };

      // 获取当前流程节点json数据以及状态
      var getQuneeStateAndData = function() {
        ManagerProcessQuneeServ.getManagerProcessQuneeStateAndData({
          id: processId
        })
        .then(function(ret) {
          var quneeState;

          if (ret.status === 200) {

            // 模拟点击执行后 数据返回的状态为 2
            // var pl_ex_id = ParseMapServ.getItem(processId, 'process');
            var pl_ex_id = execId;

            // 获取1级状态 0 基本 1 检测中 2 执行中
            quneeState = ret.results.status;
            // ManagerProcessQuneeServ.getNodeJsonTest()
            // .then(function(result) {
              // 模拟读nodeJson
              // ret.results.pipeline = result;
            switch (quneeState) {

              // 如果是默认状态 则判断chekced内的状态
              case 0:
                // var pl_ex_id = ParseMapServ.getItem(processId, 'process') || ret.results.exec_pipeline_id;
                var pl_ex_id = ret.results.exec_pipeline_id;

                // 判断是否检测过
                if (!!ret.results.checked) {
                  $scope.init = true;

                  if (!!ret.results.checked.ended_at) {
                    $scope.lastCheckDateStr = '上次检测时间: ' + ret.results.checked.ended_at.replace('T', ' ').replace('Z','');
                  };

                  $scope.lastCheckStatus = ret.results.checked.status;

                  $scope.pipeline = ret.results.pipeline;

                  console.log(JSON.parse($scope.pipeline));

                  // 保存在全局的节点列表
                  $scope.nodeList = quneeParseNodeJSON(ret.results.pipeline, ret.results.checked.check_nodes);
                  $scope.initEditor();

                  // quneeStateMap
                  // if (typeof ret.results.checked.status === 'number') {
                  //   $scope.quneeState = quneeStateMap[ret.results.checked.status];
                  // } else {
                  //   $scope.quneeState = ret.results.checked.status || 'init';
                  // };
                  $scope.quneeState = 'init';

                  if (pl_ex_id) {
                    // $scope.quitState = ParseMapServ.getItem(processId, 'quitState');
                    // $scope.quneeState = 'init';
                    $scope.quitState = 'manualQuit';
                    $scope.quneeState = 'init'
                  };

                } else {
                  $scope.pipeline = ret.results.pipeline;

                  // 保存在全局的节点列表中
                  $scope.nodeList = quneeParseNodeJSON(ret.results.pipeline);

                  $scope.initEditor();
                  $scope.quitState = ParseMapServ.getItem(processId, 'lastState');
                  $scope.quneeState = 'init';
                };
                updateQuneeStateBtn();
                break;

              // 如果是检测中 则状态为检测中
              case 1:
                var groupNodes = [];
                var selfJson;

                if (typeof ret.results.status === 'number') {
                  $scope.quneeState = quneeStateMap[ret.results.status];
                } else {
                  $scope.quneeState = ret.results.status;
                };

                $scope.pipeline = ret.results.pipeline;
                $scope.nodeList = quneeParseNodeJSON(ret.results.pipeline, ret.results.checked.check_nodes);
                $scope.initEditor(function() {

                  // 先获取全部node
                  selfJson = JSON.parse($scope.getChartJSON());

                  // 先渲染socket推送过来的节点
                  selfJson && selfJson.datas.map(function(selfItem, index) {

                    if (selfItem._className === 'Q.Node' && !!selfItem.json.properties.data.$ref) {
                      groupNodes.push({
                        index: index,
                        item: selfItem,
                        ref: selfItem.json.properties.data.$ref
                      });
                    };
                  });
                  var resukt_nodeList = dupRemove($scope.changeNodeList);
                  resukt_nodeList.map(function(node, index) {

                    // 更新节点数据 只会改变单个节点
                    selfJson.datas.map(function(selfItem, index) {

                      // 更新普通节点
                      if (selfItem._className === 'Q.Node') {
                        var refId;

                        // 判断id是否存在 不存在则为组
                        if (!!!selfItem.json.properties.data.id) {
                          refId = selfItem.json.properties.data.$ref;
                          selfItem.json.properties.data = selfJson.refs[refId];
                        };

                        if (selfItem.json.properties.data.id === node.id) {
                          selfItem.json.properties.data.infoData.status = node.status;
                          updateNode = selfItem.json.properties.data;
                          getNodeData(selfItem.json.properties.data, selfItem.json);
                          $scope.isShowDialog = (nodeStatusMap[node.status] === 'waitUserConfirm' && selfItem.json.properties.data.infoData.type === 'userConfirmNode');

                          if ($scope.isShowDialog) {
                            $scope.quneeState = 'waitConfirmOrSubmit';
                            $scope.socketPullData('pause');
                          };
                        };
                      };
                    });
                  });
                  updateJSON(selfJson);
                  $scope.quneeState = 'check';
                  $scope.socketPullData('check');
                  updateQuneeStateBtn();
                });
                break;

              // 如果是执行中 调用其他接口获取执行的具体状态
              case 2:
                var groupNodes = [];
                var selfJson;
                execId = ret.results.exec_pipeline_id;
                $scope.pipeline = ret.results.pipeline;
                $scope.nodeList = quneeParseNodeJSON(ret.results.pipeline, ret.results.checked.check_nodes);

                var lastState = nodeStatusMap[ret.results.checked.status];

                if (ret.results.checked.status === 5) {
                  lastState = 'running';
                };

                $scope.lastState = lastState;

                // 初始化节点流程图
                $scope.initEditor(function() {

                  // 先获取全部node
                  selfJson = JSON.parse($scope.getChartJSON());

                  // 先渲染socket推送过来的节点
                  selfJson && selfJson.datas.map(function(selfItem, index) {

                    if (selfItem._className === 'Q.Node' && !!selfItem.json.properties.data.$ref) {
                      groupNodes.push({
                        index: index,
                        item: selfItem,
                        ref: selfItem.json.properties.data.$ref
                      });
                    };
                  });
                  var resukt_nodeList = dupRemove($scope.changeNodeList);
                  resukt_nodeList.map(function(node, index) {
                    selfJson.datas.map(function(selfItem, index) {

                      // 更新普通节点
                      if (selfItem._className === 'Q.Node') {

                        var refId;

                        // 判断id是否存在 不存在则为组
                        if (!!!selfItem.json.properties.data.id) {
                          refId = selfItem.json.properties.data.$ref;
                          selfItem.json.properties.data = selfJson.refs[refId];
                        };

                        if (selfItem.json.properties.data.id === node.id) {
                          selfItem.json.properties.data.infoData.status = node.status;
                          updateNode = selfItem.json.properties.data;
                          getNodeData(selfItem.json.properties.data, selfItem.json);
                        };
                      };
                    });
                  });
                  updateJSON(selfJson);
                  $scope.getQuneeExecState(ret.results.exec_pipeline_id);

                  if (!!ret.results.exec_pipeline_id) {
                    $scope.getManagerProcessQuneeLogList(ret.results.exec_pipeline_id);
                  };
                });
                break;
              default:
            };
            // });
          } else {

          };
        });
      };

      // 获取执行的具体状态
      var getQuneeExecState = function(execId) {
        ManagerProcessQuneeServ.getManagerProcessQuneeExecState({
          id: execId
        })
        .then(function(ret) {

          if (ret.status === 200) {

            if (ret.results.result_status === 13) {
              $scope.lastState = 'pause';
              $scope.quneeState = 'pause';
            }
            else if (ret.results.result_status === 6){

              if ($scope.lastState !== 'check') {
                $scope.quneeState = 'pause';
              };

              $scope.lastState = 'pause';
            }
            else if (ret.results.result_status === 7){

              // 执行中 但节点错误
              $scope.quneeState = 'pause';
              $scope.lastState = 'parseError';
            }
            else if (ret.results.result_status === 10){

              // 执行中 但节点错误
              $scope.quneeState = 'pause';
              $scope.lastState = 'waitUserConfirm';
            };

            $scope.socketPullData($scope.lastState);
            updateQuneeStateBtn();

            // 模拟保存上次执行后的实际状态 执行中 / 暂停
            var lastState = ParseMapServ.getItem(processId, 'lastState');
            var result_exec_nodes = [];
            $scope.quitState = ParseMapServ.getItem(processId, 'quitState');

            if (lastState) {
              ret.results.status = lastState;
              $scope.quneeState = ret.results.status;
            } else {

              if (typeof ret.results.status === 'number') {
                $scope.quneeState = runningMap[ret.results.status] || 'running';
              } else {
                $scope.quneeState = ret.results.status;
              };
            };

            ParseMapServ.setItem(processId, ret.results.pl_ex_id, 'process');

            // 去重获取最终结果
            var resukt_nodeList = dupRemove($scope.changeNodeList);

            // 去除socket中存在的节点 不在重复渲染
            ret.results.exec_nodes.map(function(item, index) {

              resukt_nodeList.map(function(socketItem) {

                if (item.node_id === socketItem.id) {
                  // 删除http中socket存在的节点
                  ret.results.exec_nodes.splice(index, 1);
                };
              });
            });

            // [0,5] + [1,2,3,4] = [0,1,2,3,4,5]
            result_exec_nodes = ret.results.exec_nodes.concat(resukt_nodeList);

            if (!!result_exec_nodes && result_exec_nodes.length > 0) {
              var groupNodes = [];
              var selfJson = JSON.parse($scope.getChartJSON());

              selfJson.datas.map(function(selfItem, index) {

                if (selfItem._className === 'Q.Node' && !!selfItem.json.properties.data.$ref) {
                  groupNodes.push({
                    index: index,
                    item: selfItem,
                    ref: selfItem.json.properties.data.$ref
                  });
                };
              });

              result_exec_nodes.map(function(node, index) {
                selfJson.datas.map(function(selfItem, index) {

                  // 更新普通节点
                  if (selfItem._className === 'Q.Node') {

                    var refId;

                    // 判断id是否存在 不存在则为组
                    if (!!!selfItem.json.properties.data.id) {
                      refId = selfItem.json.properties.data.$ref;
                      selfItem.json.properties.data = selfJson.refs[refId];
                    };

                    if (selfItem.json.properties.data.id === node.node_id) {
                      selfItem.json.properties.data.infoData.status = node.status;
                      updateNode = selfItem.json.properties.data;
                      getNodeData(selfItem.json.properties.data, selfItem.json);
                    };
                  };
                });
              });
              updateJSON(selfJson);
            };

            updateQuneeStateBtn();
          } else {

          };
        });
      };

      // 获取流程节点
      var getQuneeState = function() {
        ManagerProcessQuneeServ.getManagerProcessQuneeState()
        .then(function(result) {
          if (result.status === 200) {
            $scope.quneeState = result.results.state;
            updateQuneeStateBtn();
          };
        });
      };

      var onStateChange = function(evt, data) {

        // 所有标识状态的集合
        var tagStatusMap = {
          requesting: {
            status: 'qunee-status label label-info',
            text: '正在请求中'
          },

          check: {
            status: 'qunee-status label label-info',
            text: '流程检测中'
          },

          checkSuccess: {
            status: 'qunee-status label label-success bg-green',
            text: '检测成功'
          },

          checkError: {
            status: 'qunee-status label label-danger',
            text: '检测异常'
          },

          running: {
            status: 'qunee-status label label-info',
            text: '流程执行中'
          },

          runError: {
            status: 'qunee-status label label-danger',
            text: '检测异常'
          },

          pause: {
            status: 'qunee-status label label-info',
            text: '流程已暂停'
          },

          parseError: {
            status: 'qunee-status label label-danger',
            text: '执行错误'
          },

          st_pausing: {
            status: 'qunee-status label label-info',
            text: '流程已暂停'
          },

          continue: {
            status: 'qunee-status label label-info',
            text: '流程执行中'
          },

          quit: {
            status: 'qunee-status label label-danger',
            text: '流程被手工终止',
            processQuit: true
          },

          manualQuit: {
            status: 'qunee-status label label-danger',
            text: '流程被手工终止',
            processQuit: true
          },

          st_stopping: {
            status: 'qunee-status label label-danger',
            text: '流程被手工终止',
            processQuit: true
          },

          runSuccess: {
            status: 'qunee-status label label-success bg-green',
            text: '流程执行成功',
            processQuit: true
          },

          runSuccessAndNodeError: {
            status: 'qunee-status label label-danger ',
            text: '流程执行完成但节点有错误',
            processQuit: true
          },

          noApproval: {
            status: 'qunee-status label label-danger',
            text: '不认可',
            processQuit: true
          },

          takeOverSucc: {
            status: 'qunee-status label label-success bg-green',
            text: '手工接管后的执行结果：成功',
            processQuit: true
          },

          takeOverError: {
            status: 'qunee-status label label-danger',
            text: '手工接管后的执行结果：失败',
            processQuit: true
          },

          waitUserConfirm: {
            status: 'qunee-status label label-info',
            text: '等待用户确认'
          }
        };

        var status = tagStatusMap[data].status;
        var text = tagStatusMap[data].text;
        $scope.processQuit = !!tagStatusMap[data].processQuit;
        console.log('$scope.processQuit', $scope.processQuit);
        $node.find('.qunee-status').removeClass().addClass(status);
        $node.find('.qunee-status').text(text);
      };

      // 推送消息
      var onPushNodeData = function(data) {

        // 保存组内节点
        var groupNodes = [];
        var selfJson = JSON.parse($scope.getChartJSON());

        // 判断是否去组内去找
        var flag = true;
        // $scope.$apply(function() {

        if (!!data.log) {
          data.log.created_at = DateParseServ.dateParse(data.log.created_at);
          $scope.logList.push(data.log);
          $timeout(function() {
            var scrollTop = $node.find('.htrd-c-qunee-log')[0].scrollHeight;
            $node.find(".htrd-c-qunee-log").scrollTop(scrollTop);
          }, 1000);
        };

        if (!!data.node) {
          selfJson && selfJson.datas.map(function(item, index) {
            var model = item.json.properties.data;

            if (model.id === data.node.id) {

              if (model.infoData.type === 'startNode' && model.infoData.status === 6) {
                $scope.quneeState = 'running';

                // 改变流程状态标示的状态
                $scope.socketPullData($scope.quneeState);
                updateQuneeStateBtn();
              };

              flag = false;
            };
          });

          // 判断是否在group内
          if (flag) {
            $scope.nodeList && $scope.nodeList.groups.map(function(group) {

              group.nodes.map(function(item) {
                var model = item.infoData;

                if (data.node.id === item.id) {

                  if (quneeRefTypeMap[item.infoData.ref_type] === 'startNode' && data.node.status === 6) {
                    $scope.quneeState = 'running';

                    // 改变流程状态标示的状态
                    $scope.socketPullData($scope.quneeState);
                    updateQuneeStateBtn();
                  };
                };
              });
            });
          };
          $scope.changeNodeList.push(data.node);
        };

        if (!!selfJson) {
          selfJson.datas.map(function(selfItem, index) {

            if (selfItem._className === 'Q.Node' && !!selfItem.json.properties.data.$ref) {
              groupNodes.push({
                index: index,
                item: selfItem,
                ref: selfItem.json.properties.data.$ref
              });
            };
          });

          if (data.node) {
            var nodeFlag = true;

            // 更新节点数据 只会改变单个节点
            selfJson.datas.map(function(selfItem, index) {

              // 更新普通节点
              if (selfItem._className === 'Q.Node') {
                var refId;

                // console.log('selfItem', selfItem);

                // 判断id是否存在 不存在则为组
                if (!!!selfItem.json.properties.data.id) {
                  refId = selfItem.json.properties.data.$ref;
                  selfItem.json.properties.data = selfJson.refs[refId];
                };

                if (selfItem.json.properties.data.id === data.node.id) {
                  selfItem.json.properties.data.infoData.status = data.node.status;
                  updateNode = selfItem.json.properties.data;
                  // console.log('getNodeData');

                  console.log('selfItem.json.properties', selfItem.json.properties);
                  console.log('data.node', data.node);
                  getNodeData(selfItem.json.properties.data, selfItem.json);
                  $scope.isShowDialog = (nodeStatusMap[data.node.status] === 'waitUserConfirm' && selfItem.json.properties.data.infoData.type === 'userConfirmNode');
                  nodeFlag = false;

                  if ($scope.isShowDialog) {
                    $scope.quneeState = 'waitConfirmOrSubmit';
                    $scope.socketPullData('pause');
                  };
                };
              };
            });


            // console.log('end selfJson', selfJson);

            updateJSON(selfJson);

            //console.log(JSON.parse($scope.getChartJSON()));

            if ($scope.isShowDialog) {
              $scope.userConfirmModel = $scope.userConfirmModel || {};
              $scope.userConfirmModel.node_id = updateNode.id;
              $scope.userConfirmModel.is_exec = 1;

              // if (!!!strapModal) {
              //   strapModal = DialogServ.modal({
              //     'scope': $scope,
              //     'templateUrl': 'view/console/modal/quneeEditorWaitConfirmOrSubmit.html'
              //   });
              //   strapModal.$promise.then(strapModal.show);
              // };
            };
          };

          if (typeof data.status === 'number') {
            $scope.quneeState = nodeStatusMap[data.status];

            if (data.status === 8) {
              $scope.socketPullData('runError');
            };

            if (data.status === 9) {
              $scope.socketPullData('runSuccess');
            };

            if (data.status === 11) {
              $scope.quitState = 'pause';
              $scope.quneeState = 'manualQuit';
              $scope.socketPullData('manualQuit');
            };

            // 正在检测
            if (data.status === 0) {

              if (data.check_status === 1) {
                $scope.quitState = 'running';
                $scope.quneeState = 'check';
              };

              if (data.check_status === 5) {

                // 单独检测
                $scope.isCheck = true;
                $scope.quneeState = 'checkSuccess';
              };

              if (data.check_status === 2) {

                // 单独检测
                $scope.isCheck = true;
                $scope.quneeState = 'checkError';
              };

              $scope.socketPullData($scope.quneeState);
            };

            // 执行中
            if (data.check_status === 5) {

              if (data.status === 6) {

                // 是执行 -> 检测
                $scope.isCheck = false;
                $scope.quneeState = 'running';
              }
              else if (data.status === 0){

                // 单独检测
                $scope.isCheck = true;
                $scope.quneeState = 'checkSuccess';

                // 代表此时是检测完成
                if (!!data.check_result && !!(data.check_result.type === 'EC')) {
                  $scope.hostErrorCount = data.check_result.host_err;
                  $scope.scriptErrCount = data.check_result.script_err;
                  $scope.$apply(function() {
                    $scope.lastCheckDateStr = '上次检测时间: ' + data.check_result.ended_at.replace('T', ' ').replace('Z','');
                  });
                  $scope.checkErrorMsg = '检测成功';
                  strapModal = DialogServ.modal({
                    'scope': $scope,
                    'templateUrl': 'view/console/modal/quneeEditorCheckResult.html'
                  });
                  strapModal.$promise.then(strapModal.show);
                };
              }
              else if (data.status === 2) {
                $scope.hostErrorCount = data.check_result.host_err;
                $scope.scriptErrCount = data.check_result.script_err;
                $scope.$apply(function() {
                  $scope.lastCheckDateStr = '上次检测时间: ' + data.check_result.ended_at.replace('T', ' ').replace('Z','');
                });
                $scope.checkErrorMsg = '脚本错误 ' + $scope.scriptErrCount + ' 个, 主机错误' + $scope.hostErrorCount + ' 个';
                strapModal = DialogServ.modal({
                  'scope': $scope,
                  'templateUrl': 'view/console/modal/quneeEditorCheckResult.html'
                });
                strapModal.$promise.then(strapModal.show);
                $scope.quneeState = 'checkError';
              }
              else if (data.status === 7) {
                console.log('执行错误');

                // 执行错误
                $scope.quneeState = 'parseError';
                $scope.socketPullData($scope.quneeState);
              }
              else if (data.status === 10) {
                console.log('用户确认暂停');

                // 执行错误
                // $scope.quneeState = 'pause';
                $scope.socketPullData($scope.quneeState);
                strapModal = DialogServ.modal({
                  'scope': $scope,
                  'templateUrl': 'view/console/modal/quneeEditorWaitConfirmOrSubmit.html'
                });
                strapModal.$promise.then(strapModal.show);
                //$scope.quneeState = 'waitConfirmOrSubmit';
              }

              else if (data.status === 19) {
                console.log('用户确认不认可终止');

                $scope.quneeState = 'manualQuit';
                $scope.socketPullData('noApproval');
              }

              else if (data.status === 20) {
                console.log('执行完成但有错误');

                // 执行错误
                $scope.quneeState = 'runSuccessAndNodeError';
                $scope.socketPullData($scope.quneeState);
              }

              else if (data.status === 21) {
                console.log('手工接管后的执行结果：成功停止');

                // 执行错误
                $scope.quneeState = 'takeOverSucc';
                $scope.socketPullData($scope.quneeState);
              }

              else if (data.status === 22) {
                console.log('手工接管后的执行结果：失败停止');

                // 执行错误
                $scope.quneeState = 'takeOverError';
                $scope.socketPullData($scope.quneeState);
              };
            };

            if (data.check_status === 2) {

              if (data.status === 2) {
                $scope.quneeState = 'runError';
                $scope.socketPullData($scope.quneeState);
              };

              if (data.status === 7) {

                $scope.quneeState = 'checkError';
                $scope.socketPullData($scope.quneeState);
              };

              if (data.status === 0) {
                $scope.quneeState = 'checkError';
                $scope.hostErrorCount = data.check_result.host_err;
                $scope.scriptErrCount = data.check_result.script_err;
                $scope.$apply(function() {
                  $scope.lastCheckDateStr = '上次检测时间: ' + data.check_result.ended_at.replace('T', ' ').replace('Z','');
                });
                $scope.checkErrorMsg = '脚本错误 ' + $scope.scriptErrCount + ' 个, 主机错误 ' + $scope.hostErrorCount + ' 个';
                strapModal = DialogServ.modal({
                  'scope': $scope,
                  'templateUrl': 'view/console/modal/quneeEditorCheckResult.html'
                });
                strapModal.$promise.then(strapModal.show);
                $scope.socketPullData($scope.quneeState);
              };
            };

            if (data.status === 20 && data.check_status === 5) {

              // 流程执行成功但有错误
              $scope.quneeState = 'runSuccessAndNodeError';
              $scope.socketPullData($scope.quneeState);
            };
            updateQuneeStateBtn();
          };
        };
      };

      var onQuneeInfo = function(evt, data) {
        $scope.$apply(function() {
          $scope.processInfoState = !$scope.processInfoState;
          $scope.historyListState = false;
          $scope.nodeInfoState = false;
        });
      };

      var onQuneeHistory = function(evt, data) {
        $scope.$apply(function() {
          $scope.historyListState = !$scope.historyListState;
          $scope.processInfoState = false;
          $scope.nodeInfoState = false;
        });
      };

      // 检测
      var onQuneeCheck = function(evt, data) {

        console.log('检测')

        if ($scope.stateConfig.check) {
          $scope.quneeState = 'check';

          // 重置所有节点
          resetNodes();

          // 改变流程摁键组的状态
          updateQuneeStateBtn();

          // 改变流程状态标示的状态
          $scope.socketPullData('requesting');
          ManagerProcessQuneeServ.ManagerProcessQuneeCheck({
            id: processId
          })
          .then(function(ret) {

            if (ret.status !== 200) {
              // $scope.quneeState = 'checkSuccess';
              $scope.quneeState = 'checkError';
              // 改变流程状态标示的状态
              $scope.socketPullData($scope.quneeState);
              updateQuneeStateBtn();
            };
          });

        };
      };


      // 点击执行
      var onQuneeStart = function(evt, data) {

        if ($scope.stateConfig.start) {

          // 重置所有节点
          resetNodes();

          // 改变流程状态标示的状态
          $scope.socketPullData('requesting');
          $node.find('.qunee-start').addClass('default btn-outline').attr("disabled", true);
          $node.find('.qunee-start i').removeClass().addClass('htrd-icon-random-click');
          $node.find('.qunee-check').addClass('default btn-outline').attr("disabled", true);
          $node.find('.qunee-check i').removeClass().addClass('htrd-icon-check-click');
          ManagerProcessQuneeServ.ManagerProcessQuneeStart({
            id: processId
          })
          .then(function(ret) {

            if (ret.status === 200) {

              var updateNode;
              $node.find('.qunee-start').removeClass('default btn-outline').attr("disabled", false);
              $node.find('.htrd-l-bg-black i').removeClass().addClass('htrd-icon-random');
              ParseMapServ.setItem(processId, ret.results.pl_ex_id, 'process');
              execId = ret.results.pl_ex_id;
              $scope.stateConfig.start = !!!$scope.stateConfig.start;
              $scope.quneeState = 'check';

              // 改变流程状态标示的状态
              $scope.socketPullData($scope.quneeState);
              updateQuneeStateBtn();
            } else {
              AlertServ.showError(ret.msg);
            };
          });
        };
      };

      // 暂停
      var onQuneePause = function(evt, data) {

        if ($scope.stateConfig.pause) {
          $scope.socketPullData('requesting');
          $node.find('.qunee-pause').addClass('default btn-outline').attr("disabled", true);
          $node.find('.qunee-pause i').removeClass().addClass('htrd-icon-pause-click');

          if (!!!execId) {
            // execId = ParseMapServ.getItem(processId, 'process');
          };

          ManagerProcessQuneeServ.ManagerProcessQuneePause({
            id: execId
          })
          .then(function(ret) {

            if (ret.status === 200) {
              $timeout(function() {
                $node.find('.qunee-pause').removeClass('default btn-outline').attr("disabled", false);
                $node.find('.qunee-pause i').removeClass().addClass('htrd-icon-pause');
                $scope.quneeState = 'pause';
                $scope.socketPullData($scope.quneeState);
                updateQuneeStateBtn();
                // AlertServ.showSuccess(ret.msg);
              }, 2000);
            } else {
              AlertServ.showError(ret.msg);
            };
          });
        };
      };

      // 继续
      var onQuneeContinue = function(evt, data) {

        if ($scope.stateConfig.continue) {
          var updateNode;
          $scope.socketPullData('requesting');
          $node.find('.qunee-continue').addClass('default btn-outline').attr("disabled", true);
          $node.find('.qunee-continue i').removeClass().addClass('htrd-icon-random-click');
          ManagerProcessQuneeServ.ManagerProcessQuneeContinue({
            id: execId
          })
          .then(function(ret) {

            if (ret.status === 200) {
              $scope.quneeState = 'running';
              // $timeout(function() {
              $node.find('.qunee-continue').removeClass('default btn-outline').attr("disabled", false);
              $node.find('.qunee-continue i').removeClass().addClass('htrd-icon-random-click');
              $scope.socketPullData($scope.quneeState);
              updateQuneeStateBtn();
              // }, 2000);
            } else {
              AlertServ.showError(ret.msg);
            };
          });
        };
      };

      // 终止
      var onQuneeQuit = function(evt, data) {

        if ($scope.stateConfig.quit) {

          strapModal = DialogServ.modal({
            'scope': $scope,
            'templateUrl': 'view/console/modal/quneeEditorQuit.html'
          });
          strapModal.$promise.then(strapModal.show);
        };
      };

      // 重做本节点
      var onQuneeRestartSelfNode = function(evt, data) {
        console.log('$scope.processQuit', $scope.processQuit);

        // 流程已经终止了
        if ($scope.processQuit) {
          AlertServ.showSuccess('流程已结束 , 无法操作');
          return false;
        };

        $scope.isShowDialog = (!!(data.type === 'userConfirmNode' && data.status === 10));

        if ($scope.isShowDialog) {
          $scope.userConfirmModel = $scope.userConfirmModel || {};
          $scope.userConfirmModel.id = data.id;
          $scope.userConfirmModel.node_id = data.nodeId;
          $scope.toggleRadio(1);
        } else {
          ManagerProcessQuneeServ.ManagerProcessQuneeResetNode({
            id: execId,
            node_id: data.nodeId
          })
          .then(function(ret) {

            if (ret.status === 200) {
              AlertServ.showSuccess('请求成功');
            } else {
              AlertServ.showError('请求失败');
            };
          });
        };
      };

      // 手工接管
      var onQuneeManualNozzleNode = function(evt, data) {
        console.log('$scope.processQuit', $scope.processQuit);

        // 流程已经终止了
        if ($scope.processQuit) {
          AlertServ.showSuccess('流程已结束 , 无法操作');
          return false;
        };

        if (!!!data.disabled) {
          $scope.userEditorTakeOverModel.id = data.id;
          strapModal = DialogServ.modal({
            'scope': $scope,
            'templateUrl': 'view/console/modal/quneeEditorTakeOver.html'
          });
          strapModal.$promise.then(strapModal.show);
        };
      };

      // 切换日志显示状态
      var toggleLog = function() {
        $scope.logShowState = !!!$scope.logShowState;
      };

      var getNodeData = function(data, node, isGroup) {
        var type, status, info;

        if (isGroup) {
          type = quneeRefTypeMap[data.infoData.ref_type];

          if (node.status && typeof node.status === 'string') {
            status = node.infoData.status;
          } else {
            status = nodeStatusMap[node.status] || 'init';
          };
          info = $scope.statusNodeMap[type][status];
          data.image = info.icon;
          data.menuList = info.menuList;
          data.status = status;
          data.type = type;
        } else {
          type = data.infoData.type || quneeRefTypeMap[data.infoData.ref_type];

          if (data.infoData.status && typeof data.infoData.status === 'string') {
            status = data.infoData.status;
          } else {
            status = nodeStatusMap[data.infoData.status] || 'init';
          };
          info = $scope.statusNodeMap[type][status];

          if (info) {
            node.image = info.icon;
            node.menuList = info.menuList;
          };
        };
      };

      // 创建折线
      // from 起点
      // to终点
      // pathSegmentList 中间坐标
      var createEdge = function(graph, from, to, pathSegmentList) {
        var edge = graph.createEdge('edge', from, to);
        pathSegmentList && pathSegmentList.map(function(item) {
          edge.addPathSegment([item.x, item.y]);
        });
        return edge;
      };

      // 创建组节点
      var createGroup = function (groupData, expanded, graph) {
        var graph = graph || $window.editor.graph;
        expanded = expanded !== false;
        var group = graph.createGroup(groupData.name);

        group.expanded = expanded;
        var groupHandle = new Q.LabelUI(expanded ? "-" : "+");
        groupHandle.backgroundColor = "#2898E0";
        groupHandle.color = "#FFF";
        groupHandle.padding = new Q.Insets(0, 4);
        groupHandle.borderRadius = 0;
        groupHandle.position = Q.Position.RIGHT_TOP;
        groupHandle.anchorPosition = Q.Position.LEFT_TOP;
        groupHandle.type = "GroupHandle";
        groupHandle.reverseExpanded = function(evt){
            var g = this.parent.data;
            g.expanded = !g.expanded;
        }
        group.addUI(groupHandle, {
            property : "expanded",
            callback: function(value, ui){
              ui.data = value ? "-" : "+";
            }
        });
        return group;
      };

      // 解析json
      var translateToQuneeElements = function(json, graph){
          var map = {};
          var graph = graph || $window.editor.graph;

          // 创建普通节点
          if (json.nodes) {
              Q.forEach(json.nodes, function(data){
                  var node = graph.createNode(data.name, data.x || 0, data.y || 0);
                  getNodeData(data, node);
                  node.set("data", data);
                  map[data.id] = node;
              });
          };

          // 创建组
          if (json.groups) {
              Q.forEach(json.groups, function(data){
                  var group = createGroup(data, true, graph);
                  getNodeData(data, group);
                  data.nodes.map(function(item){

                    // 子组
                    var innerNode = graph.createNode(item.name, item.x, item.y);
                    getNodeData(item, innerNode);
                    innerNode.set("data", item);
                    map[item.id] = innerNode;
                    group.addChild(innerNode);
                  });

                  group.set("data", data);
                  map[data.id] = group;
              });
          };

          // 创建连线
          if (json.edges) {
              Q.forEach(json.edges, function(data){
                  var from = map[data.from];
                  var to = map[data.to];

                  if(!from || !to){
                      return;
                  };

                  // data.pathSegmentList = [
                  //   {
                  //     x: 100,
                  //     y: 200
                  //   }
                  // ];

                  var edge = createEdge(graph, from, to, data.infoData.pathList);
                  edge.set("data", data);
              }, graph);
          };
      };


      // 显示右侧信息
      var onShowNodeInfo = function(evt) {
        console.log('onShowNodeInfo');
        var data = evt.getData();
        var nodeId;

        // 是否点击到空白处
        if (!!!data) {
          $scope.$apply(function() {
            $scope.historyListState = false;
            $scope.processInfoState = false;
            $scope.nodeInfoState = false;
          });
        } else {

          if (data instanceof Q.Group) {
              var target = $window.editor.graph.hitTest(evt);

              if (target && target.type == "GroupHandle") {
                  target.reverseExpanded();
              } else {
                nodeId = data._n0w.data.id;
                $scope.nodeInfo = {
                  id: nodeId
                };

                $scope.$apply(function() {
                  $scope.historyListState = false;
                  $scope.processInfoState = false;
                  $scope.nodeInfoState = true;
                });
              }
          } else {
            nodeId = data._n0w.data.id;
            $scope.nodeInfo = {
              id: nodeId
            };

            $scope.$apply(function() {
              $scope.historyListState = false;
              $scope.processInfoState = false;
              $scope.nodeInfoState = true;
            });
          }
        };
      };

      var initQuneeEvent = function() {
        editor.graph.onclick = onShowNodeInfo;
      };

      // 获取加载完成的json
      var getChartJSON = function() {

        if (!!$window.editor) {
          return editor.graph.exportJSON(true, {space: '  '});
        } else {
          return null;
        };
      };

      var initEditor = function(callback) {
        console.log('editor')
        $node.find('.editor').graphEditor({
          callback: function(editor){
            // editor.graph.delayedRendering = true;
            translateToQuneeElements($scope.nodeList, editor.graph);
            editor.graph.moveToCenter();
            $window.editor = editor;
            var selfJson = JSON.parse($scope.getChartJSON());
            initQuneeEvent();
            $timeout(function () {
              editor.graph.zoomToOverview();
            }, 100);
            callback && callback();
          }
        });
      };

      // 局部刷新流程图
      var updateJSON = function(data) {
        editor.submitJSON(data);
      };

      var parseDOM = function() {
        $scope = s;
        $node = $(e[0]);
        $window.$quneeNode = $node;
      };

      var bindListener = function() {
        $scope.getQuneeNodeInfo = getQuneeNodeInfo;
        $scope.getQuneeProcessInfo = getQuneeProcessInfo;
        $scope.getQuneeHistoryList = getQuneeHistoryList;
        $scope.getManagerProcessQuneeLogList = getManagerProcessQuneeLogList;
        $scope.getUserList = getUserList;
        $scope.createGroup = createGroup;
        $scope.translateToQuneeElements = translateToQuneeElements;
        $scope.initEditor = initEditor;
        $scope.updateJSON = updateJSON;
        $scope.getChartJSON = getChartJSON;
        $scope.initQuneeEvent = initQuneeEvent;
        $scope.toggleLog = toggleLog;
        $scope.getQuneeState = getQuneeState;
        $scope.getQuneeStateAndData = getQuneeStateAndData;
        $scope.getQuneeExecState = getQuneeExecState;
        $scope.submitUserConfirm = submitUserConfirm;
        $scope.activeUser = activeUser;
        $scope.submitEditorTakeOver = submitEditorTakeOver;
        $scope.submitProcessQuit = submitProcessQuit;
        $scope.socketPullData = socketPullData;
        $scope.toggleRadio = toggleRadio;
        $scope.toggleTakeRadio = toggleTakeRadio;

        // 监听qunee 所有事件
        $node.on('qunee.check', onQuneeCheck);
        $node.on('qunee.start', onQuneeStart);
        $node.on('qunee.pause', onQuneePause);
        $node.on('qunee.continue', onQuneeContinue);
        $node.on('qunee.quit', onQuneeQuit);
        $node.on('qunee.restartSelfNode', onQuneeRestartSelfNode);
        $node.on('qunee.manualNozzleNode', onQuneeManualNozzleNode);
        $node.on('qunee.stateChange', onStateChange);

        $node.on('qunee.info', onQuneeInfo);
        $node.on('qunee.history', onQuneeHistory);
      };

      var initPlugins = function() {
        $scope.logList = [];
        $scope.changeNodeList = [];

        // 保存当前流程id
        processId = $stateParams.id;
        $scope.processId = processId;

        // 初始化socket链接
        SocketServ.initSocket(processId);
        SocketServ.onMessage(onPushNodeData);
        SocketServ.onClose();
        SocketServ.onError();

        $timeout(function() {
          SocketServ.sendMessage('test')
        }, 20000)

        // 只监听跳转路由
        $rootScope.$on('$stateChangeStart', function() {

          // 如果状态不为终止 执行成功 的话 则清除执行id
          if ($scope.quneeState === 'manualQuit' || $scope.quneeState === 'execSuccess') {
            ParseMapServ.removeItem(processId, 'quitState');
            ParseMapServ.removeItem(processId, 'process');
          };
        });

        // execId = ParseMapServ.getItem(processId, 'process') || 0;


        $scope.selectDefaultText = '请选择用户';
        $scope.stateConfig = {
          check: true,
          start: true,
          pause: true,
          quit: true
        };

        // 用户接管表单参数
        $scope.userEditorTakeOverModel = {
          check: 1,
          resultQuery: true,
          remark: ''
        };

        $scope.userEditorQuitModel = {
          remark: ''
        };

        // 初始化参数
        $scope.historyListState = false;
        $scope.nodeInfoState = false;
        $scope.logShowState = false;
        $scope.processInfoState = false;

        // 所有节点状态字典
        ManagerProcessQuneeServ.getManagerProcessQuneeStateMap()
        .then(function(result) {
          $scope.statusNodeMap = result;
          $window.statusNodeMap = result;
          getQuneeStateAndData();
        });

        $scope.getUserList();
        $scope.getQuneeHistoryList();
        $scope.getQuneeProcessInfo();
        $node.find('.htrd-c-button-group').hide();
      };

      var init = function() {
        parseDOM();
        bindListener();
        initPlugins();
      };

      init();
  };

  return {
      'replace': true,
      'restrict' : 'AEC',
      'scope': {
        'config': '='
      },
      'link': link,
      'templateUrl': 'view/directive/util/quneeEditer.html'
  };
}]);
